#include <myhead.h>
#include <memory.h>
typedef struct student
{
	char name[20];
	int id;
	double chinese;
	double math;
	double english;
	double physical;
	double chemical;
	double biological;
}stu_t;
//将数组中学生所有信息保存到文件
void save_stu(stu_t*,int,const char*);
//将文件中所有学生信息读取到新数组中，并输出
void load_stu(const char*,stu_t*);
//清除无用信息
int my_txt(FILE*);
//
int main(int argc, const char *argv[])
{
	stu_t arr[3]=
	{
		{"张三",1001,92.3,92.4,92.7,90.2,92.5,92.8},
		{"李四",1002,82.5,82.6,82.4,80.5,86.5,86.3},
		{"王五",1003,70.2,70.3,70.4,70.5,72.5,75.5}
	};
	int len =sizeof(arr)/sizeof(stu_t);
	printf("数组长度为：%d\n",len);
	stu_t arr2[1000];
	save_stu(arr,len,argv[1]);
	load_stu(argv[1],arr2);
	return 0;
}

void save_stu(stu_t *arr,int len,const char *l)
{
	FILE*p=fopen(l,"a");
	if(p==NULL)
	{
		printf("打开文件失败\n");
		return;
	}
	for(int i=0;i<len;i++)
	{
		fprintf(p,"%s","姓名:");
		fprintf(p,"%-10s",arr[i].name);
		fprintf(p," %s","学号:");
		fprintf(p,"%-8d",arr[i].id);
		fprintf(p," %s","语文成绩:");
		fprintf(p,"%-5.1lf",arr[i].chinese);
		fprintf(p," %s","数学成绩:");
		fprintf(p,"%-5.1lf",arr[i].math);
		fprintf(p," %s","英语成绩:");
		fprintf(p,"%-5.1lf",arr[i].english);
		fprintf(p," %s","物理成绩:");
		fprintf(p,"%-5.1lf",arr[i].physical);
		fprintf(p," %s","化学成绩:");
		fprintf(p,"%-5.1lf",arr[i].chemical);
		fprintf(p," %s","生物成绩:");
		fprintf(p,"%-5.1lf",arr[i].biological);
		fprintf(p,"%c",10);
	}
	printf("输出至文件成功\n");
	fclose(p);
}
//
void load_stu(const char*l,stu_t*arr)
{
	FILE*p=fopen(l,"r");
	if(p==NULL)
	{
		printf("打开文件失败\n");
		return;
	}
	int n=0;
	while(1)
	{
		if(my_txt(p)==-1) break;
		fscanf(p,"%s",arr[n].name);
		if(my_txt(p)==-1) break;
		fscanf(p,"%d",&arr[n].id);
		if(my_txt(p)==-1) break;
		fscanf(p,"%lf",&arr[n].chinese);
		if(my_txt(p)==-1) break;
		fscanf(p,"%lf",&arr[n].math);
		if(my_txt(p)==-1) break;
		fscanf(p,"%lf",&arr[n].english);
		if(my_txt(p)==-1) break;
		fscanf(p,"%lf",&arr[n].physical);
		if(my_txt(p)==-1) break;
		fscanf(p,"%lf",&arr[n].chemical);
		if(my_txt(p)==-1) break;
		fscanf(p,"%lf",&arr[n].biological);
		printf("姓名：%s  学号：%-8d  成绩： %-8lf  %-8lf  %-8lf %-8lf %-8lf %-8lf\n"
				,arr[n].name
				,arr[n].id
				,arr[n].chinese
				,arr[n].math
				,arr[n].english
				,arr[n].physical
				,arr[n].chemical
				,arr[n].biological);
		n++;
	}
	fclose(p);
	
	return;
}


int my_txt(FILE* p)
{
	int a;
	//printf("吸收注释：");
	while(1) 
	{
		a=fgetc(p);
		if(a==EOF||a==':')
		{
	//		printf("清除完成--%c\n",a);
			break;
		}
	}
	if(a==EOF)return-1;
	if(a==':')return 0;
}
